using AutoMapper;
using MediatR;
using RBAC.Domain.SmartHealthcare;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using SmartHealthcare.Read.Api.Application.Command.Department;
using SmartHealthcare.Read.Api.DTo;

namespace SmartHealthcare.Read.Api.Application.Handler.Department
{
    /// <summary>
    /// 获取科室及其病例信息处理器
    /// </summary>
    public class GetDepartmentWithCasesHandler : IRequestHandler<GetDepartmentWithCasesCommand, APIResult<List<DepartmentWithCasesDto>>>
    {
        private readonly IBaseRepository<CaseModel> _caseRepository;
        private readonly IBaseRepository<DepartmentModel> _departmentRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<GetDepartmentWithCasesHandler> _logger;

        public GetDepartmentWithCasesHandler(
            IBaseRepository<CaseModel> caseRepository, 
            IBaseRepository<DepartmentModel> departmentRepository, 
            IMapper mapper, 
            ILogger<GetDepartmentWithCasesHandler> logger)
        {
            _caseRepository = caseRepository;
            _departmentRepository = departmentRepository;
            _mapper = mapper;
            _logger = logger;
        }
        /// <summary>
        /// 获取科室及下级所有案例
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIResult<List<DepartmentWithCasesDto>>> Handle(GetDepartmentWithCasesCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<DepartmentWithCasesDto>> res = new APIResult<List<DepartmentWithCasesDto>>();
            
            try
            {
                // 获取所有未删除的科室数据
                var departmentsQuery = _departmentRepository.GetALL().Where(x => x.IsDeleted == false);
                
                var departments = departmentsQuery.ToList();
                
                // 获取所有未删除的病例数据
                var cases = _caseRepository.GetALL().Where(x => x.IsDeleted == false).ToList();

                // 构建科室及其病例的分组数据
                var departmentWithCasesList = departments.Select(dept => new DepartmentWithCasesDto
                {
                    Id = dept.Id,
                    DepartmentCode = dept.DepartmentCode,
                    DepartmentName = dept.DepartmentName,
                    Address = dept.Address,
                    RegistrationMoney = dept.RegistrationMoney,
                    IsEmergency = dept.IsEmergency,
                    Cases = cases.Where(c => c.DepartmentId == dept.Id)
                                .Select(c => new CaseDto
                                {
                                    Id = c.Id,
                                    DepartmentId = c.DepartmentId,
                                    CaseName = c.CaseName,
                                    CreateTime = c.CreateTime,
                                    CreateUser = c.CreateUser
                                }).ToList()
                }).ToList();

                res.Data = departmentWithCasesList;
                res.Code = APIEnums.Success;
                res.Msg = "查询成功";
                _logger.LogInformation("科室病例分组查询成功，共查询到 {DepartmentCount} 个科室，{CaseCount} 个病例", 
                    departmentWithCasesList.Count, 
                    departmentWithCasesList.Sum(d => d.CaseCount));
                
                return Task.FromResult(res);
            }
            catch (Exception ex)
            {
                res.Code = APIEnums.Fail;
                res.Msg = "查询失败";
                res.Data = new List<DepartmentWithCasesDto>();
                _logger.LogError(ex, "科室病例分组查询失败");
                
                return Task.FromResult(res);
            }
        }
    }
}
